<template>
	<div class="table">
		<div class="crumbs">
				<el-breadcrumb separator="/">
						<el-breadcrumb-item>
								<i class="el-icon-menu"></i>{{$route.name}}
						</el-breadcrumb-item>
				</el-breadcrumb>
		</div>
		<div class="handle-box">
				<el-dialog :title="title" :visible.sync="dialogFormVisible" class="expert">
						<el-form :model="addForm" inline :rules="rules" ref="addForm">
								<el-form-item label="名称" :label-width="formLabelWidth" prop="name">
										<el-input v-model="addForm.name" auto-complete="off"></el-input>
								</el-form-item>
								<el-form-item label="所属机构" :label-width="formLabelWidth">
                                    <el-select v-model="addForm.organizationId" placeholder="请选择所属机构">
                                            <el-option v-for="org in orgs" :key="org.id" :label="org.name" :value="org.id"></el-option>
                                    </el-select>
								</el-form-item>
								<el-form-item label="职位" :label-width="formLabelWidth">
										<el-input type="textarea" v-model="addForm.job" auto-complete="off"></el-input>
								</el-form-item>
								<el-form-item label="排名" :label-width="formLabelWidth">
										<el-input v-model="addForm.ranking" auto-complete="off"></el-input>
								</el-form-item>
								<el-form-item label="教育背景" :label-width="formLabelWidth">
										<el-input v-model="addForm.edu" auto-complete="off"></el-input>
								</el-form-item>
								<el-form-item label="报告" :label-width="formLabelWidth">
										<el-input type="textarea" v-model="addForm.report" auto-complete="off"></el-input>
								</el-form-item>
								<el-form-item label="论文" :label-width="formLabelWidth">
										<el-input type="textarea" v-model="addForm.paper" auto-complete="off"></el-input>
								</el-form-item>
								<el-form-item label="著作" :label-width="formLabelWidth">
										<el-input type="textarea" v-model="addForm.book" auto-complete="off"></el-input>
								</el-form-item>
								<el-form-item label="名字首字母大写" :label-width="formLabelWidth" prop="nameChar">
										<el-input v-model="addForm.nameChar" auto-complete="off"></el-input>
								</el-form-item>
								<el-form-item label="研究领域类型" :label-width="formLabelWidth">
                                    <el-select v-model="fieldIds" multiple placeholder="请选择研究领域类型">
                                        <el-option v-for="domain in domains" :key="domain.id" :label="domain.research_field_name" :value="domain.id">
                                        </el-option>
                                    </el-select>
								</el-form-item>
								<el-form-item label="用户头像" :label-width="formLabelWidth">
                                    <el-upload
                                        action=""
                                        class="avatar-uploader" 
                                        ref="upload"
                                        accept="image/*"
                                        :http-request="upload"
                                        :show-file-list="false" 
                                        v-loading.fullscreen.lock="fullscreenLoading" 
                                    >
                                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                    </el-upload>
								</el-form-item>
						</el-form>
						<div slot="footer" class="dialog-footer">
								<el-button @click="cancel">取 消</el-button>
								<el-button type="primary" @click="update">确 定</el-button>
						</div>
				</el-dialog>
				<el-input v-model="select_word" placeholder="输入专家名称" class="search"></el-input>
				<el-button type="primary" icon="search" @click="search">搜索</el-button>
				<el-button type="primary" @click="addExp">新增专家</el-button>
		</div>
		<div>
				<el-table :data="tableData" border fit style="width: 100%" v-loading="loading">
						<el-table-column label="头像" fixed prop="img">
								<template slot-scope="scope">
										<img :src="scope.row.img" width="100%" height="100%" />
								</template>
						</el-table-column>
						<el-table-column prop="name" label="名称" fixed></el-table-column>
                        <el-table-column prop="nameChar" label="名字首字母大写" fixed></el-table-column>
						<el-table-column prop="organizationId" label="所属机构" show-overflow-tooltip :formatter="orgFormatter">
						</el-table-column>
						<el-table-column prop="job" label="职位" show-overflow-tooltip empty-text>
						</el-table-column>
						<el-table-column prop="ranking" label="排名" show-overflow-tooltip empty-text>
						</el-table-column>
						<el-table-column prop="edu" label="教育背景" show-overflow-tooltip>
						</el-table-column>
						<el-table-column prop="report" label="报告" show-overflow-tooltip empty-text>
						</el-table-column>
						<el-table-column prop="paper" label="论文" show-overflow-tooltip empty-text>
						</el-table-column>
						<el-table-column prop="book" label="著作" show-overflow-tooltip empty-text>
						</el-table-column>
                        <el-table-column prop="state" label="状态" show-overflow-tooltip empty-text :formatter="stateFormatter">
						</el-table-column>
						<el-table-column 
                            prop="research_field_list" 
                            label="研究领域类型" 
                            show-overflow-tooltip 
                            empty-text
                            :formatter="researchFormatter"
						>
						</el-table-column>
						<el-table-column fixed="right" label="操作">
								<template slot-scope="scope">
										<el-button @click="edit(scope.row)" type="text" size="small">编辑</el-button>
										<el-button type="text" size="small" @click="delUser(scope.row)">删除</el-button>
                                        <el-switch
                                            v-model="scope.row.state === 1 ? true : false"
                                            active-color="#13ce66"
                                            @change="switchChange(scope.row)"
                                        >
                                    </el-switch>
								</template>
						</el-table-column>
				</el-table>
		</div>
		<div class="block">
				<el-pagination @current-change="handleCurrentChange" :current-page="page.number" 
				layout="total, prev, pager, next, jumper" :total="page.total">
				</el-pagination>
				</el-pagination>
		</div>
	</div>
</template>
<script>
import { expert, uploadFile } from "../../server/getDate.js";
import { mapState, mapActions } from 'vuex'
import { getStore, getObjectURL, filterObj } from '../../utils/local.js'
const { allExpert, addProfessor, deleteApi, updateApi, disableTypeApi, orgs } = expert
const domainsApi = expert.domains
export default {
    data() {
        return {
            value: '',
            loading: false,
            dialogTableVisible: false,
            dialogFormVisible: false,
            dialogFormUpdate: false,
            select_word: '',
            title: '',
            addForm: {
                organizationId: [],
            },
            fieldIds: [],
            imageUrl: '',
            formLabelWidth: '120px',
            show: false,
            fullscreenLoading: false,
            rules: {
                name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
                nameChar: [{ required: true, message: '请输入名字首字母大写', trigger: 'blur'}, {
                    pattern: /^[A-Z]*$/, message: '只支持A-Z大写'
                }],
            }
        }
    },
    created() {
        this.getExpert(1)
        this.getAllDomain()
        this.getAllOrgs()
    },
    computed: mapState({
        page: state => state.Expert.page,
        tableData: state => state.Expert.list,
        orgs: state => state.Org.org,
        domains: state => state.Expert.domains,
        orgs: state => state.Expert.orgs
    }),
    methods: {
        ...mapActions(['save_expert', 'add_expert', 
        'save_domain', 'save_orgs']),
        getExpert(number) {
            const params = {
                page: number,
                pageSize: 10
            }
            if (this.select_word !== '') {
                params.searchKey = this.select_word
            }
            allExpert({
                ...params
            }).then(res => {
                if (res.code === '000000') {
                    this.save_expert({
                        ...res,
                        number
                    })
                } else {
                    this.$message.error(res.message)
                }
            }, err => { this.$message.error(err.message) })
        },
        getAllDomain() {
            domainsApi().then(res => {
                if (res.code === '000000') {
                    this.save_domain(res)
                } else {
                    this.$message.error(res.message)
                }
            }, err => this.$message.error('网络错误'))
        },
        getAllOrgs() {
            orgs().then(res => {
                if (res.code === '000000') {
                    this.save_orgs(res)
                } else {
                    this.$message.error(res.message)
                }
            }, () => {
                this.$message.error('网络错误')
            })
        },
        researchFormatter(row, col) {
            const list = row.research_field_list
            if (list.length === 0) {
                return '无研究领域'
            } else {
                const names = list.map(item => {
                    if (item && item.research_field_name) {
                        return item.research_field_name
                    }
                })
                return names.join(',')
            }
        },
        stateFormatter(row) {
            const state = row.state
            return state === 1 ? '启用' : '禁用'
        },
        orgFormatter(row) {
            const list = this.orgs
            if (list.length === 0) {
                return '无所属机构'
            } else {
                let org = ''
                list.some(item => {
                    if (row.organizationId === item.id) {
                        org = item.name
                        return true
                    }
                })
                return org
            }
        },
        search() {
            this.getExpert(this.page.number)
        },
        handleCurrentChange(val) {
            this.getExpert(val)
        },
        delUser(row) {
            this.$confirm('此操作将永久删除该专家, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let id = row.id
                deleteApi({ ids: id })
                    .then(res => {
                        if (res.code === '000000') {
                            this.getExpert(this.page.number)
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }
                    })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        add() {
            this.$refs['addForm'].validate(valid => {
                if (valid) {
                    this.addForm.fieldIds = this.fieldIds.join(',')
                    addProfessor({ ...this.addForm })
                        .then(res => {
                            if (res.code === '000000') {
                                this.dialogFormVisible = false
                                this.$message.info("添加成功")
                                this.getExpert(this.page.number)
                            } else {
                                this.$message.error(res.message)
                            }
                        }, err => this.$message.error("网络异常"))     
                }
            })
        },
        addExp() {
            this.dialogFormVisible = true
            this.title = '新增专家'
            this.addForm = {}
            this.fieldIds = []
            this.imageUrl = ''
        },
        edit(row) {
            this.title = '修改专家'
            this.dialogFormVisible = true
            this.addForm = filterObj(row)
            this.imageUrl = this.addForm.img
            const lists = row.research_field_list
            if (lists && lists.length > 0) {
                this.fieldIds = lists.map(item => {
                    return item.id
                })
            }
        },
        putExpert() {
            this.addForm.fieldIds = this.fieldIds.join(',')
            updateApi({ ...this.addForm })
                .then(res => {
                    if (res.code === '000000') {
                        this.dialogFormVisible = false
                        this.$message.success('修改成功')
                        this.getExpert(this.page.number)
                    } else {
                        this.$message.error(res.message)
                    }
                }, err => this.$message.error(res.message))
        },
        upload(file) {
            this.fullscreenLoading = false
            let formData = new FormData()
            formData.append('fileName', file.file);
            formData.append('fileType', '1')
            uploadFile(formData, res => {
                if (res.code === '000000') {
                    this.imageUrl = res.result.storageName
                    this.addForm.img = this.imageUrl
                } else {
                    this.$message.error(res.message)
                }
            })
        },
        update() {
            if (this.addForm.id) {
                this.putExpert()
            } else {
                this.add()
            }
        },
        cancel() {
            this.dialogFormVisible = false
        },
        switchChange(row) {
            disableTypeApi({ 
                ids: row.id, 
                state: row.state ? '0' : '1'
            }).then(res => {
                if (res.code === '000000') {
                this.$message.success('修改成功')
                this.getExpert(this.page.number)
                } else {
                this.$message.error(res.message)
                }
            }, () => {
                this.$message.error('网络错误')
            })
        }
    }
}
</script>
<style lang="scss" scoped>
.handle-box {
  margin-bottom: 1%;
  .search {
    width: 30%;
  }
}

:global {
    .el-input {
        width: 400px;
    }
    .el-select {
        width: 400px;
    }
    .el-textarea {
        width: 400px;
    }
}

.block {
  text-align: center;
  margin-top: 1%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
